//
// Created by Administrator on 2022/12/17.
//

#include "JavaCallHelper.h"

JavaCallHelper::JavaCallHelper(JavaVM *_javaVM, JNIEnv *_env, jobject &_jobj) {
    this->javaVm = _javaVM;
    this->env = _env;
    this->jobj = this->env->NewGlobalRef(_jobj);
    jclass jclass1 = this->env->GetObjectClass(this->jobj);
    callMethodId = this->env->GetMethodID(jclass1, "postData", "([B)V");
}

JavaCallHelper::~JavaCallHelper() {

    this->env->DeleteGlobalRef(this->jobj);
}

void JavaCallHelper::callData(char *data, int length, int thread) {

  jbyteArray array =  this->env->NewByteArray(length);
  this->env->SetByteArrayRegion(array, 0, length, reinterpret_cast<const jbyte *>(data));
    if (thread==THREAD_MAIN) {
        this->env->CallVoidMethod(this->jobj,this->callMethodId,array);
    } else {
        JNIEnv *jniEnv;
        if (this->javaVm->AttachCurrentThread(&jniEnv,0)!=JNI_OK) {
            return;
        }
        jniEnv->CallVoidMethod(this->jobj,this->callMethodId,array);
        this->javaVm->DetachCurrentThread();
    }
}
